import { defineStore } from 'pinia';
import { http } from '@/utils/request';

interface UserInfo {
  id: string;
  username: string;
  avatar: string;
  phone: string;
}

interface UserState {
  token: string;
  userInfo: UserInfo | null;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: uni.getStorageSync('token') || '',
    userInfo: null
  }),

  getters: {
    isLoggedIn(): boolean {
      return !!this.token;
    }
  },

  actions: {
    // 设置Token
    setToken(token: string) {
      this.token = token;
      uni.setStorageSync('token', token);
    },

    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },

    // 登录
    async login(phone: string, password: string) {
      try {
        const res = await http.post<{ token: string; userInfo: UserInfo }>('/api/user/login', {
          phone,
          password
        });
        
        this.setToken(res.data.token);
        this.setUserInfo(res.data.userInfo);
        return res;
      } catch (error) {
        throw error;
      }
    },

    // 获取用户信息
    async getUserInfo() {
      try {
        const res = await http.get<UserInfo>('/api/user/info');
        this.setUserInfo(res.data);
        return res;
      } catch (error) {
        throw error;
      }
    },

    // 退出登录
    logout() {
      this.token = '';
      this.userInfo = null;
      uni.removeStorageSync('token');
    }
  }
}); 